package com.gzhryc.pay.adaptation.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.gzhryc.common.NumberTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.pay.adaptation.alipay.enums.AliTransferMoneyType;
import com.gzhryc.pay.adaptation.alipay.msg.AliReceivingInfo;
import com.gzhryc.pay.models.ITransferMoneyOrder;

import java.io.Serializable;
import java.util.Properties;

public class AlipayTransferMoneyService implements Serializable {

    private static final long serialVersionUID = 1L;

	static Logger log = Logger.getLogger(AlipayTransferMoneyService.class);

    DefaultAlipayConfig config;

    public AlipayTransferMoneyService(){}

    public AlipayTransferMoneyService(Properties properties) {
        this.config = PropertyTools.build(properties).getObject(DefaultAlipayConfig.class);
    }

    public AlipayTransferMoneyService(DefaultAlipayConfig config) {
        this.config = config;
    }

    public AlipayFundTransUniTransferResponse applyTransferMoney(ITransferMoneyOrder transferMoneyOrder) {
        AlipayFundTransUniTransferResponse response = null;
        try {
            DefaultAlipayClient httpClient = AliHttpClient.getHttpClient(config);

            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            AliTransferMoneyType aliTransferMoneyType = AliTransferMoneyType.type(transferMoneyOrder.getReceivingType());
            if (aliTransferMoneyType == null)
                return null;
            String receivingInfoJson = transferMoneyOrder.getReceivingInfo();
            AliReceivingInfo receivingInfo = JsonTools.fromJson(receivingInfoJson, AliReceivingInfo.class);
            request.setBizContent("{" + "\"out_biz_no\":\"" + transferMoneyOrder.getTradeNo() + "\"," + "\"trans_amount\":"
                    + NumberTools.changeMoney(transferMoneyOrder.getMoney()) + "," + "\"product_code\":\"" + aliTransferMoneyType.productCode() + "\","
                    + "\"biz_scene\":\"" + aliTransferMoneyType.bizScene() + "\"," + "\"order_title\":\"支付宝转账\"," + "\"payee_info\":{" + "\"identity\":\""
                    + receivingInfo.getAccountId() + "\"," + "\"identity_type\":\"ALIPAY_USER_ID\","
                    + "\"name\":\"" + receivingInfo.getName() + "\"," + "    }," + "\"remark\":\"" + transferMoneyOrder.getNote() + "\"," + "  }");

            response = httpClient.certificateExecute(request);
        } catch (AlipayApiException e) {
            log.error(e.getMessage(), e);
        } catch (LogicException e) {
            log.error(e.getMessage(), e);
        }
        return response;
    }
}
